﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Configuration;
using System.Linq.Expressions;

namespace Freedom.Common
{
    #region LINQ通用类
    /// <summary>
    /// LINQ通用类 构建一个泛型类，DataBase:指代参数类型,where表示约束
    /// </summary>
    /// <typeparam name="DataBase"></typeparam>
    public class LinqHelper<DataBase> where DataBase : DataContext, new()
    {
        private DataBase dc;//数据上下文对象
        private bool IsDeferred = true;//是否启用延迟加载

        #region 获得数据库连接
        /// <summary>
        /// 获得数据库连接
        /// </summary>
        /// <returns></returns>
        public DataBase GetConn()
        {
            //实例化数据上下文
            DataBase dc = new DataBase();
            //创建数据库连接字符串
            dc.Connection.ConnectionString = ConfigurationManager.AppSettings["db_FreedomConnectionString"];
            return dc;
        }
        #endregion

        #region 查询所有数据
        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public List<T> GetList<T>() where T : class
        {
            //获得数据上下文
            dc = GetConn();
            //是否启用延迟加载
            if (IsDeferred)
            {
                dc.DeferredLoadingEnabled = true;
                return dc.GetTable<T>().ToList();
            }
            dc.DeferredLoadingEnabled = false;
            return dc.GetTable<T>().ToList();
        }
        #endregion

        #region 条件查询
        /// <summary>
        /// 条件查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public List<T> GetList<T>(Expression<Func<T, bool>> predicate) where T : class
        {
            dc = GetConn();
            //是否延迟加载
            if (IsDeferred)
            {
                dc.DeferredLoadingEnabled = true;
                return dc.GetTable<T>().Where(predicate).ToList();
            }
            dc.DeferredLoadingEnabled = false;
            return dc.GetTable<T>().Where(predicate).ToList();
        }
        #endregion

        #region 判断数据是否存在
        /// <summary>
        /// 判断数据是否存在
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="predicate">Lambda表达式</param>
        /// <returns></returns>
        public bool EntityExists<T>(Expression<Func<T, bool>> predicate) where T : class
        {
            dc = GetConn();
            //是否为延迟加载
            if (IsDeferred== true)
            {
                dc.DeferredLoadingEnabled = false;
                return dc.GetTable<T>().Where<T>(predicate).Count() > 0;
            }
            dc.DeferredLoadingEnabled = true;
            return dc.GetTable<T>().Where<T>(predicate).Count() > 0;
        }
        #endregion

        #region 新增实体
        /// <summary>
        /// 新增实体
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="entity">实体</param>
        public void InsertEntity<T>(T entity) where T : class
        {
            using (dc = GetConn())
            {
                //添加实体到集合中
                dc.GetTable<T>().InsertOnSubmit(entity);
                //提交到数据库
                dc.SubmitChanges();
            }
        }
        #endregion

        #region 更新实体
        /// <summary>
        /// 更新实体
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="Entity">实体</param>
        public void UpdateEntity<T>(T Entity) where T : class
        {
            using (DataBase db = GetConn())
            {               
                //附加新实体
                db.GetTable<T>().Attach(Entity);
                //刷新集合，保存当前对象
                db.Refresh(RefreshMode.KeepCurrentValues, Entity);
                //提交到数据库，防止并发操作
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
        }
        #endregion

        #region 删除实体
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void DeleteEntity<T>(Expression<Func<T, bool>> predicate) where T : class
        {
            ////判断记录是否存在
            //if (EntityExists<T>(predicate))
            //{
            try
            {
                using (dc = GetConn())
                {
                    //查询
                    var list = dc.GetTable<T>().Where<T>(predicate).Single();
                    //从集合中删除
                    dc.GetTable<T>().DeleteOnSubmit(list);
                    //提交到数据库
                    dc.SubmitChanges();
                }
            }
            catch (Exception)
            {
                
                throw;
            }
               
            //}

        }
        #endregion

        #region 分页
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="list">分页数据源</param>
        /// <param name="pageSize">每页的条数</param>
        /// <param name="pageIndex">显示页数</param>
        /// <returns></returns>
        public List<T> GetPage<T>(List<T> list, int pageSize, int pageIndex) where T : class
        {
            return list.Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize).ToList<T>();
        }
        #endregion

        #region 使用sql语句查询
        /// <summary>
        /// 使用sql语句查询
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public List<T> GetListBySql<T>(string sql) where T : class
        {
            dc = GetConn();
            return dc.ExecuteQuery<T>(sql, "").ToList<T>();
        }
        #endregion
    }
    #endregion
}
